package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IVerifyCodeCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Assert;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private IVerifyCodeCacheService verifyCodeCacheService;

    @Override
    public AjaxResult userLogin(String phone, String password){
        AjaxResult ajaxResult = new AjaxResult();
        UserInfo userInfo = userInfoMapper.selectByPhoneAndPassword(phone, password);
        if(userInfo == null){
            ajaxResult.mark("账号密码不匹配");
        }else{
            ajaxResult.setData(userInfo);
        }
        return ajaxResult;
    }

    @Override
    public boolean checkPhone(String phone) {
        //查询有对象就不为null,返回false表示不可以注册
        return userInfoMapper.selectPhoneExists(phone) == null;
    }

    @Override
    public AjaxResult userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //先用断言判断数据合法性(不为空)
            Assert.hasLength(phone, "手机号码不能为空");
            Assert.hasLength(nickname, "昵称不能为空");
            Assert.hasLength(password, "密码不能为空");
            Assert.hasLength(rpassword, "确认密码不能为空");
            Assert.hasLength(verifyCode, "验证码不能为空");
            //判断两次密码是否一致(密码是区分大小写的)
            Assert.equals(password, rpassword, "两次输入密码必须一致");
            //判断验证码是否正确(可以不区分大小写)
            String vc = verifyCodeCacheService.getVerifyCodeCache(phone);
            Assert.equalsIgnoreCase(verifyCode, vc, "验证码不正确");
            //将参数封装对象,设置默认值
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            userInfo.setPassword(password);
            userInfo.setPhone(phone);
            userInfo.setGender(UserInfo.GENDER_NONE);
            userInfo.setLevel(1);
            //数据库insert
            userInfoMapper.insert(userInfo);
        }catch (Exception e){
            ajaxResult.mark(e.getMessage());
        }
        return ajaxResult;
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }
}
